﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Configuration;
using MySql.Data.MySqlClient;
using MySql.Data;
using OnlineCooperation.Entity;

namespace OnlineCooperation.DB
{
    public class TopicDB
    {
        String strConn;
        datasetMgn DSMgn;

        //构造函数， 为strConn赋值
        public TopicDB()
        {
            strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            DSMgn = new datasetMgn();
        }

        /// <summary>
        /// 向数据库中插入一条话题记录，使得第一次出现在post中##引出的内容成为一个新的话题（即：创建话题）
        /// </summary>
        /// <param name="topic">话题，其ID字段初始为无效字段</param>
        /// <returns>插入的结果：返回1成功，返回0表示该团队已存在该话题，插入失败</returns>
        public int Insert(Topic topic)
        {
            String strSql = "SELECT  * FROM `topic` WHERE `TopicContent`=\'" + topic.Content + "\' AND `TopicTeamID` ='" + topic.TeamID + "'";
            DataSet ds = DSMgn.ReadDataSet(strSql, strConn);
            if (ds.Tables[0].Rows.Count != 0)
                return 0;

            strSql = "INSERT INTO `topic`(`TopicContent`,`TopicTeamID`) VALUES(?TopicContent2, ?TopicTeamID2)";
            MySqlParameter[] parameters2 = new MySqlParameter[2];
            parameters2[0] = new MySqlParameter("?TopicContent2", MySqlDbType.VarChar);
            parameters2[0].Value = topic.Content;
            parameters2[1] = new MySqlParameter("?TopicTeamID2", MySqlDbType.Int32);
            parameters2[1].Value = topic.TeamID;
            MySqlHelper.ExecuteNonQuery(strConn, strSql, parameters2);

            return 1;
        }

        /// <summary>
        /// 在数据库中根据内容查询到特定话题
        /// </summary>
        /// <param name="content">内容</param>
        /// <returns>查询结果：若查询到，则返回该话题；否则返回ID为-1的话题</returns>
        public Topic GetTopicByContent(String content, int teamid)
        {
            String strSql = "SELECT * FROM `topic` WHERE `TopicContent`=\'" + content + "\' AND `TopicTeamID`='" + teamid + "'";
            DataSet ds = DSMgn.ReadDataSet(strSql, strConn);
            if (ds.Tables[0].Rows.Count == 0)
            {
                Topic topic = new Topic();
                topic.ID = -1;
                return topic;
            }                                                                                                    //该团队不存在该内容的话题，查询失败
            else
            {
                Topic topic = new Topic(Convert.ToInt32(DSMgn.Readstr(strSql, 0, strConn)), DSMgn.Readstr(strSql, 1, strConn), teamid);
                return topic;
            }                                                                                                    //查询成功
        }
    }
}